import 'package:distribution_mall_flutter/entity/goods/list/goods_list_entity.dart';
import 'package:distribution_mall_flutter/http/modules/goods.dart';
import 'package:distribution_mall_flutter/pages/home/widgets/tab.dart';
import 'package:distribution_mall_flutter/provider/home/waterfall.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

part 'home_goods_provider.g.dart';

int pageSize = 20;

@riverpod
class HomeGoods extends _$HomeGoods {
  @override
  HomeGoodsData build(String tag) {
    refreshData(tag);
    return HomeGoodsData.init(tabName.first == tag
        ? <Item>[
            _item..saleUnitId = 'test_1',
            _item..saleUnitId = 'test_2',
            _item..saleUnitId = 'test_3',
            _item..saleUnitId = 'test_4',
            _item..saleUnitId = 'test_5',
            _item..saleUnitId = 'test_6',
          ]
        : []);
  }

  ///刷新数据
  Future<void> refreshData(String tag) async {
    (await GoodsApi.goodsSuSearch(tag: tag, pageNum: 1, pageSize: pageSize))
        .yes((apiData) {
      List<Item> data = apiData?.pageResult?.items ?? [];
      state = state.copyWith(data: data, page: 2);
      // 是第一个tag才调用，防止出现假数据
      if (tabName.first == tag) {
        ref.read(waterfallProvider.notifier).setFirstLoadingIsFalse();
      }
    }).no((_) {
      if (tabName.first == tag &&
          ref.read(waterfallProvider).firstLoading &&
          state.page == 1) {
        state = state.copyWith(data: []);
      }
      // 是第一个tag才调用，防止出现假数据
      if (tabName.first == tag) {
        ref.read(waterfallProvider.notifier).setFirstLoadingIsFalse();
      }
    });
  }

  ///加载数据
  Future<IndicatorResult> onLoadMore(String tag) async {
    var result = (await GoodsApi.goodsSuSearch(
        tag: tag, pageNum: state.page, pageSize: pageSize));
    if (result.hasSuccess) {
      var apiData = result.data;
      List<Item> data = apiData?.pageResult?.items ?? [];
      state =
          state.copyWith(data: [...state.data, ...data], page: state.page + 1);
      return data.length >= pageSize
          ? IndicatorResult.success
          : IndicatorResult.noMore;
    } else {
      return IndicatorResult.success;
    }
  }

  setGoodStayTime(String key, {DateTime? start, DateTime? end, String? tag}) {
    if (key == '') return;
    if (state.goodStayTime[key] == null && start != null) {
      state.goodStayTime[key] = {'start': '${start.millisecondsSinceEpoch}'};
      return;
    } else if (state.goodStayTime[key] != null && end != null) {
      int i = int.parse(state.goodStayTime[key]?['start'] ?? '0');
      if (i == 0) return;
      state.goodStayTime[key] = {
        'time': end
            .difference(DateTime.fromMillisecondsSinceEpoch(i))
            .inSeconds
            .toString(),
        'tag': tag ?? ''
      };
    }
  }
}

@riverpod
class HomeGoodsStay extends _$HomeGoodsStay {
  @override
  HomeGoodsStayData build() {
    return HomeGoodsStayData();
  }

  setGoodStayTime(String key, {DateTime? start, DateTime? end, String? tag}) {
    if (key == '') return;
    if (state.goodStayTime[key] != null &&
        state.goodStayTime[key]?['time'] != null) return;

    if (state.goodStayTime[key] == null && start != null) {
      state.goodStayTime[key] = {'start': '${start.millisecondsSinceEpoch}'};
      return;
    } else if (state.goodStayTime[key] != null && end != null) {
      int i = int.parse(state.goodStayTime[key]?['start'] ?? '0');
      if (i == 0) return;
      state.goodStayTime[key] = {
        'time': end
            .difference(DateTime.fromMillisecondsSinceEpoch(i))
            .inSeconds
            .toString(),
        'tag': tag ?? ''
      };
    }
  }

  clearGoodStayTime() {
    state.goodStayTime = {};
  }
}

class HomeGoodsData {
  List<Item> data = <Item>[];
  int page = 1;
  // 统计商品曝光时长
  Map<String, Map<String, String>?> goodStayTime = {};

  HomeGoodsData();

  HomeGoodsData.init(List<Item> initData) {
    data = initData;
  }

  HomeGoodsData copyWith(
      {List<Item>? data,
      int? page,
      Map<String, Map<String, String>?>? goodStayTime}) {
    return HomeGoodsData()
      ..data = data ?? this.data
      ..page = page ?? this.page
      ..goodStayTime = goodStayTime ?? this.goodStayTime;
  }
}

class HomeGoodsStayData {
  // 统计商品曝光时长
  Map<String, Map<String, String>?> goodStayTime = {};

  HomeGoodsStayData();

  HomeGoodsStayData.init();

  HomeGoodsStayData copyWith(
      {Map<String, Map<String, String>?>? goodStayTime}) {
    return HomeGoodsStayData()
      ..goodStayTime = goodStayTime ?? this.goodStayTime;
  }
}

final Item _item = Item()
  ..brandInfo = (BrandInfo()..brandName = 'Temporary brand replacement area')
  ..categoryInfo =
      (CategoryInfo()..categoryName = 'Temporary category replacement area')
  ..priceInfo = (PriceInfo()
    ..minSalePrice = 100
    ..maxSuggestedRetailPrice = 100);
